package com.ksy.common.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.ksy.common.qqapi.QQLoginActivity;
import com.ksy.common.utils.Constants;
import com.tencent.tauth.Tencent;

/**
 * Created by ksy on 2018/3/27.
 */

public class QQPlatform implements LoginPlatform<QQInfo> {
    private final Context context;
    private Tencent mTencent;
    private Listener listener;
    private int code = 9995;

    public interface Listener {
        void onSuccess(QQInfo qqInfo);

        void onError(String msg);

        void onCancel();
    }

    public QQPlatform(Context context) {
        this.context = context;
    }

    @Override
    public boolean isCanLogin() {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQID, context);
        }
        return mTencent.isQQInstalled(context);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != code) {
            return;
        }
        if (Login_Code_QQ_Success == resultCode) {
            //登录成功
            QQInfo qqInfo = data.getParcelableExtra("qqInfo");
            onSuccess(qqInfo);
        } else if (Login_Code_QQ_Cancel == resultCode) {
            //登录取消
            onCancel();
        } else if (Login_Code_QQ_Error == resultCode) {
            //登录失败
            onError("QQ授权失败");
        }
    }

    public void loginTo(Activity activity, Listener listener) {
        this.listener = listener;
        Intent intent = new Intent(activity, QQLoginActivity.class);
        intent.putExtra("isHand", true);
        activity.startActivityForResult(intent, code);
        activity.overridePendingTransition(0, 0);
    }

    @Override
    public void onSuccess(QQInfo qqInfo) {
        if (listener != null) {
            listener.onSuccess(qqInfo);
        }
    }

    @Override
    public void onError(String msg) {
        if (listener != null) {
            listener.onError(msg);
        }
    }

    @Override
    public void onCancel() {
        if (listener != null) {
            listener.onCancel();
        }
    }
}
